#!/usr/bin/env python
"""
simulate_partial_pattern.py

Thu Oct 11 15:24:26 CEST 2012

This script simulates the recall of an incomplete pattern
with different seeds and at different values of delta_t

To execute type in your terminal:
>>> ./simulate_partial_pattern 
"""

from network import topology
from firings import Pattern, generate
from firings import get_overlap
from plasticity import clipped_Hebbian
from STDP import delta_t 

import numpy as np

ncells = 3000 # number of cells
c = 0.5       # connection probability 
a = 0.1       # activity of a pattern
m = 50        # number of patterns to store
g1 = 0.433    # slope of inhibitory component

def create_synaptic_weights(seed):
    """
    simulate 10 progressive recalls of a partial 
    pattern at different dt according to the STDP 
    rule found experimentally

    Returns:
    The connectivity matrix 
    The original pattern to be recall
    The matrix of synaptic weights
    """
    
    W = topology(ncells, c, seed)
    Z = Pattern(ncells, a)
    Y = generate(Z, m)

    J = clipped_Hebbian(Y, W)
    return(W, Z, Y, J)


def recall(Z,J):
    """
    returns a 
    """
    # X = INCOMPLETE PATTERN
    X = np.zeros(ncells, dtype=int)
    # incomplete pattern 10% of valid firings b1=0.1
    similarity = int(ncells*a*0.1)
    X[:similarity] = 1

    # RECALL
    nrecall = 10
    
    overlap = np.empty(11, dtype=float)
    overlap[0] = get_overlap(Z, X) # first the pattern itself 

    for i in range(1, nrecall+1):
        h = np.inner(J.T, X)/float(ncells)
        spk_avg = np.mean(X)
        X = ( h < g1*spk_avg ).choose(1,0)
        overlap[i] = get_overlap(Z, X)

    return(overlap)
        

if __name__ == '__main__':
    # 50 seeds per simulation
    myseed = np.arange(0, 2500, 50)
    # 9 timmings
    mydt = np.array([-100, -50, -25, -10, 0, 10, 25, 50, 100])

    myseed_list = list()
    for s in myseed:
        W, Z, Y, J = create_synaptic_weights(seed=s)

        collecdt = np.empty([len(mydt),11])
        for j,t in enumerate(mydt):
            Jnew = J*delta_t(t)
            collecdt[j] = recall(Z, Jnew)
        myseed_list.append(collecdt)

    # reorder to save output in files
    for t, i in enumerate(mydt):
        dt_tmp = [myseed_list[x][t] for x in range(len(myseed_list))]   
        np.savetxt('./data/overlap[dt=%d].out'%(i), dt_tmp, fmt='%f')

    


